
using System;
using System.Threading;
using HelloWorld.Helper;

namespace HelloWorld.Learn
{
    public class VolatileDemo
    {
        public static void Demo()
        {
            // Create the worker thread object. This does not start the thread.
            Worker workerObject = new Worker();
            workerObject.Num = 50;
            Thread workerThread1 = new Thread(workerObject.DoWork);
            Thread workerThread2 = new Thread(workerObject.DoWork);
            Thread workerThread3 = new Thread(workerObject.DoWork);
            Thread workerThread4 = new Thread(workerObject.DoWork);

            // Start the worker thread.
            workerThread1.Start();
            Console.WriteLine("Main thread1: starting worker thread...");
            workerThread2.Start();
            Console.WriteLine("Main thread2: starting worker thread...");
            workerThread3.Start();
            Console.WriteLine("Main thread3: starting worker thread...");
            workerThread4.Start();
            Console.WriteLine("Main thread4: starting worker thread...");
            // Loop until the worker thread activates.
            while (!workerThread1.IsAlive || !workerThread2.IsAlive || !workerThread3.IsAlive || !workerThread4.IsAlive);

            // Put the main thread to sleep for 1 millisecond to
            // allow the worker thread to do some work.
            //Thread.Sleep(1);

            // Use the Thread.Join method to block the current thread 
            // until the object's thread terminates.
            workerThread1.Join();
            workerThread2.Join();
            workerThread3.Join();
            workerThread4.Join();
            Console.WriteLine("Main thread: worker thread has terminated.");
        }
    }
}